package backtrackAlgorithm;

import java.util.ArrayList;
import java.util.List;

/*
 *@description 组合总和
 *@author hkfan
 *@version 1.0
 *@create 2025/6/16 15:36
 */
public class LeetCode_39 {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        ArrayList<List<Integer>> lists = new ArrayList<>();
        solution(lists,new ArrayList<Integer>(),0,target,candidates);
        return lists;
    }

    private void solution(List<List<Integer>> lists, List<Integer> list, int index, int sum, int[] nums) {
        if (sum==0){
            lists.add(new ArrayList<>(list));
            return;
        }
        if (index> nums.length-1){
            return;
        }
        for (int i = 0; i <= sum/nums[index]; i++) {
            for (int j = 0; j < i; j++) {
                list.add(nums[index]);
            }
            solution(lists,list,index+1,sum-i*nums[index],nums);
            for (int j = 0; j < i; j++) {
                list.remove(list.size()-1);
            }
        }
    }

}
